package com.stylefeng.guns.modular.huamao.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.modular.huamao.controller.AccountShopController;
import com.stylefeng.guns.modular.huamao.dao.*;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.IAccountShopService;
import com.stylefeng.guns.modular.huamao.service.IUsersService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.huamao.common.GetOrderNum;
import com.stylefeng.guns.modular.huamao.service.IAccountService;

/**
 * <p>
 * 会员账户表 服务实现类
 * </p>
 *
 * @author gxz123
 * @since 2018-04-11
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {
	@Autowired
	private AccountMapper am;
	@Autowired
	private LogCashMapper logCashMapper;
	@Autowired
	private AccountOperationMapper accountOperationMapper;
	@Autowired
	private UsersUpgradeMapper usersUpgradeMapper;
	@Autowired
	private LogScoreMapper logScoreMapper;
	@Autowired
	private LogScoreFreezeMapper logScoreFreezeMapper;
	@Autowired
	private LogCashFreezeMapper logCashFreezeMapper;
	@Autowired
	private AccountShopMapper accountShopMapper;
	@Autowired
	private LogKaiyuanTurnoverMapper logKaiyuanTurnoverMapper;
	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private AgentsApplysMapper agentsApplysMapper;
	@Autowired
	private SktSysConfigsMapper sktSysConfigsMapper;
	@Autowired
	private LogScoreSpecialMapper logScoreSpecialMapper;
	@Autowired
	private LogStockscoreMapper logStockscoreMapper;
	@Autowired
	LogKaiyuanMapper  logKaiyuanMapper;
	@Autowired
	private  SktAgentsStockholderMapper agentsStockholderMapper;
	@Autowired
	private   SktAgentsAccountMapper agentsAccountMapper;
	@Autowired
	private LogKaiyuanFreezeMapper logKaiyuanFreezeMapper;
	@Autowired
	private SktAgentsMapper agentsMapper;

	@Autowired
	private  LogScoreAgentMapper  logScoreAgentMapper;

	@Autowired
	private 	IAccountShopService  accountShopService;

	@Autowired
	private SktBuyplaqueMapper  sktBuyplaqueMapper;

	@Autowired
	private IUsersService usersService;
	@Autowired
	SktOrdersMapper som;
	// 展示用户账户列表
	@Override
	public List<AccountList> selectAccountAll(Page<AccountList> page, AccountList accountList) {
		Integer total = am.selectAccountAllCount(accountList);
		page.setTotal(total);
		return am.selectAccountAll(page,accountList);
	}

	@Override
	public Account selectAccountByuserId(Integer userId) {
		// TODO Auto-generated method stub
		return am.selectAccountBuyuserId(userId);
	}

	@Override
	public Object getUseUpDate(Integer userId) {
		// TODO Auto-generated method stub
		return null;
	}
	@Transactional
	@Override
	public boolean updateByUp(AccountList accountList,BigDecimal changeCash){
		try {
			Account account = am.selectAccountBuyuserId(accountList.getUserId());
			//生成现金流水
			LogCash logCash=new LogCash();
			logCash.setCashType(-1);
			logCash.setCreateTime(new Date());
			logCash.setDataFlag(1);
			logCash.setFromId(0);
			logCash.setUserId(accountList.getUserId());
			// 创建订单号
			SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String strDate = sfDate.format(new Date());
			String num = GetOrderNum.getRandom620(2);
			logCash.setOrderNo("3"+strDate + num);
			logCash.setPreCash(account.getCash());
			logCash.setRemark("用户升级");
			logCash.setType(35);
			logCash.setCash(changeCash);
			logCashMapper.insert(logCash);
			//插入账户修改记录表
//			AccountOperation  accountOperation=new AccountOperation();
//			accountOperation.setCreateTime(new Date());
//			accountOperation.setDataFlag(1);
//			accountOperation.setNum(changeCash);
//			accountOperation.setObject(2);
//			
//			accountOperation.setOrderNo("8"+strDate + num);
//			accountOperation.setRemark("用户升级");
//			accountOperation.setStaffId(0);//???
//			accountOperation.setType(-1);
//			accountOperation.setUserId(accountList.getUserId());
//			accountOperationMapper.insert(accountOperation);
			//修改现金账户
			am.updateOrderRefunds(accountList);
			return true;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}
		
	}

	
	/*
	 * 取消用户升级退款
	 *
	  */
	@Transactional
	@Override
	public boolean resetUPGrade(UsersUpgrade usersUpgrade){
		try {
			Account account = am.selectAccountBuyuserId(usersUpgrade.getUserId());
			if (usersUpgrade.getStatus()==1 ||usersUpgrade.getStatus()==2 ||usersUpgrade.getStatus()==4){
				this.insertLogCash(1, 0, usersUpgrade.getUserId(), usersUpgrade.getOrderNo(), account.getCash(), "订单"+usersUpgrade.getOrderNo()  +"退款", 35, usersUpgrade.getCash());
				BigDecimal cash2 = account.getCash().add(usersUpgrade.getCash());
				account.setCash(cash2);
				am.updateById(account);
			}else if(usersUpgrade.getStatus()==3){
				this.insertLogKaiyuan(0,usersUpgrade.getKaiyuan(),1,usersUpgrade.getOrderNo(),account.getKaiyuan(),"订单"+usersUpgrade.getOrderNo()  +"退款",5, usersUpgrade.getUserId());
				account.setKaiyuan(account.getKaiyuan().add(usersUpgrade.getKaiyuan()));
				am.updateById(account);
			}else if(usersUpgrade.getStatus()==3){
				AccountShop accountShop=new AccountShop();
				accountShop.setUserId(usersUpgrade.getUserId());
				EntityWrapper<AccountShop> ew=new EntityWrapper<AccountShop>(accountShop);
				AccountShop accountShop1 = accountShopService.selectOne(ew);
				this.insertLogKaiYuanTurnover(6,0,usersUpgrade.getUserId(),usersUpgrade.getOrderNo(),accountShop1.getKaiyuanTurnover(),1,usersUpgrade.getKaiyuan(),"订单"+usersUpgrade.getOrderNo()  +"退款");
				accountShop1.setKaiyuanTurnover(accountShop1.getKaiyuanTurnover().add(usersUpgrade.getKaiyuan()));
				accountShopService.updateById(accountShop1);
			}




			return true;
			//插入账户修改记录表
//			AccountOperation  accountOperation=new AccountOperation();
//			accountOperation.setCreateTime(new Date());
//			accountOperation.setDataFlag(1);
//			accountOperation.setNum(usersUpgrade.getCash());
//			accountOperation.setObject(2);
//
//			accountOperation.setOrderNo("8"+strDate + num);
//			accountOperation.setRemark("用户升级");
//			accountOperation.setStaffId(0);//???
//			accountOperation.setType(-1);
//			accountOperation.setUserId(usersUpgrade.getUserId());
//			accountOperationMapper.insert(accountOperation);
			//修改现金账户
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}



	}


	/**  用户消费
	 * @param userId  用户id
	 * @param cash  消费金额
	 * @return
	 */
	@Override
	public boolean userSale(int userId, BigDecimal num,String saleType) {
		// TODO Auto-generated method stub
		Account account = am.selectAccountBuyuserId(userId);
		
		
		return false;
	}

	/**
	 * 用户升级后的操作
	 * @param orderId
	 * @return
	 */
	@Transactional
	@Override
	public String upAfterAdd(Integer orderId) {
	try {
		UsersUpgrade usersUpgrade = new UsersUpgrade();
		usersUpgrade.setOrderId(orderId);
		//通过订单号，查询用户信息
		usersUpgrade = usersUpgradeMapper.selectOne(usersUpgrade);
		Integer userId = usersUpgrade.getUserId();
		Boolean isManager = false;
		//判断用户是否升级经理
		if(usersUpgrade.getAfterRole() == 2){
			isManager = true;
		}
		// 操作前金额要到数据库查询account表中的实时金额，将userId传过去
		Account account = am.findScoreById(usersUpgrade.getUserId());
		/**
		 * 给用户添加积分
		 */
		LogScore logScore = new LogScore();

		// 支出人为平台设置为0
		logScore.setFromId(0);
		// 收入人为此用户
		logScore.setUserId(usersUpgrade.getUserId());
		// 积分类型为 用户升级 7
		logScore.setType(7);
		// 生成订单号
//			SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//			String strDate = sfDate.format(new Date());
//			String num = GetOrderNum.getRandom620(2);
		logScore.setOrderNo(usersUpgrade.getOrderNo());
		// 用户操作前金额
		logScore.setPreScore(account.getScore());
		// 流水标志：加积分所以类型为 1
		logScore.setScoreType(1);
		// 操作金额
		logScore.setScore(usersUpgrade.getTotalMoney().multiply(new BigDecimal(100)));
		// 备注直接生成
		logScore.setRemark("用户升级奖励");
		// 创建时间
		logScore.setCreateTime(new Date());
		// 添加积分记录
		Integer insert = logScoreMapper.insert(logScore);

		/**
		 * 给account表添加积分
		 */
		// Account account3 = am.findFreezeScoreById(userId);
		BigDecimal score=usersUpgrade.getTotalMoney().multiply(new BigDecimal(100));
		Integer update = this.updateScoreByUserId(account,score);
		// 实时查询用户账户
		// Account account2 = am.findFreezeScoreById(userId);

		/**
		 * 判断此用户是否有代发积分，如果有的话转入正式积分
		 */
		if (account.getFreezeScore().compareTo(BigDecimal.ZERO) != 0) {
			/**
			 * 将代发积分转入正式
			 */
			this.FreezeToFormal(userId, account.getFreezeScore(), isManager,usersUpgrade.getOrderNo());
		}

		/**
		 * 判断此用户是否有待发现金，有的话转入正式
		 */
		if (account.getFreezeCash().compareTo(BigDecimal.ZERO) != 0) {
			//升级经理
			if(isManager){
				//现金待发记录
				this.freezeCashToFormal(31,userId,userId,usersUpgrade.getOrderNo(),account.getFreezeCash(),-1,account.getFreezeCash(),"普通用户升级为经理，待发现金转为可用现金");
			}else{
				//现金待发记录
				this.freezeCashToFormal(31,userId,userId,usersUpgrade.getOrderNo(),account.getFreezeCash(),-1,account.getFreezeCash(),"普通用户升级为主管，待发现金转为可用现金");
			}
			/**
			 * 将待发现金转入正式
			 */
			this.cashFrrezeToFormal(userId, account.getFreezeCash(), isManager,usersUpgrade.getOrderNo());
		}

		/**
		 * 判断此用户是否是商家
		 */
		AccountShop accountShop = accountShopMapper.findShopId(userId);
		if (accountShop != null && accountShop.getShopId() != 0) {
			// 判断商家是否有待发华宝营业额
			if (accountShop.getFreezeKaiyuan() != null
					&& accountShop.getFreezeKaiyuan().compareTo(BigDecimal.ZERO) != 0) {
				/**
				 * 将待发华宝转入正式账户
				 */
				//备注
				String remark = "";
				// 判断用户升级经理还是主管
				if (isManager) {
					remark = "普通用户升级为经理，待发华宝营业额转为可用华宝营业额";
				} else {
					remark = "普通用户升级为主管，待发华宝营业额转为可用华宝营业额";
				}
				//生成待发华宝营业额流水表
				this.insertLogKaiyuanFreeze(userId,accountShop.getFreezeKaiyuan(),-1,usersUpgrade.getOrderNo(),accountShop.getFreezeKaiyuan(),remark,31,userId);
				// 生成华宝营业额流水表
				this.hbTurnover(4, userId, userId, usersUpgrade.getOrderNo(), 1, accountShop.getFreezeKaiyuan(), remark);
			}
		}

		/**
		 * 是否升级的是经理，如果是经理，查询七个工作日内是否有下线升级为代理
		 */
		if (isManager) {
			// 判断是否有下线
			List<Integer> downWires = usersMapper.findDownWires(userId);
			//如果有下线判断是否七个工作日内有升级为代理的
			if(downWires.size() > 0){
				List<AgentsApplys> agents = getAgentsApplysSevenAgo(userId);
				if (agents != null && agents.size() > 0) {
					BigDecimal sumScore = BigDecimal.ZERO;
					BigDecimal sumScoreFreeze =
							BigDecimal.ZERO;
					for (AgentsApplys AgentsApply : agents) {
						if (AgentsApply.getType() == 7) {
							sumScore = sumScore.add
									(AgentsApply.getMoney().multiply(new BigDecimal("200")));
						} else if (AgentsApply.getType() !=
								7 && AgentsApply.getType() != 6) {
							sumScoreFreeze =
									sumScoreFreeze.add(AgentsApply.getMoney().multiply(new BigDecimal("200")));
						}
					}
					if(sumScoreFreeze.compareTo(BigDecimal.ZERO)==1){
						this.insertLogScoreFreeze(0, 10, usersUpgrade.getOrderNo(),
								account.getFreezeScore(), "下线升级代理奖励", sumScoreFreeze, 1, userId);
						account.setFreezeScore
								(account.getFreezeScore().add(sumScoreFreeze));
					}
					if(sumScore.compareTo(BigDecimal.ZERO)==1){
						this.insertLogScore(0, 10, usersUpgrade.getOrderNo(),
								account.getScore(), "下线升级代理奖励", sumScore, 1, userId);
						account.setScore(account.getScore().add
								(sumScore));
						account.setTotalScore
								(account.getTotalScore().add(sumScore));
					}
					am.updateById(account);
				}
			}
		}
//		// 查询用户升级前后角色
//		UsersUpgrade usersUpgrade = usersUpgradeMapper.findUserRole(orderId);
		/**
		 * 判断直接分享人是否为空，直接分享人，现金奖励
		 */
		//查询上线
		Integer shareManId = usersMapper.findShareManId(userId);
		Users shareMan = usersMapper.findShareMan(shareManId);
		if (shareMan != null) {
			// 普通》主管 。 普通》 经理 。 主管》经理
			if (usersUpgrade.getPreRole() == 0 && usersUpgrade.getAfterRole() == 1) {
				//查询商城配置中分享人应得现金奖励
				SktSysConfigs configs = sktSysConfigsMapper.selectSysConfigsByFieldCode("directorProfit");
				// 实时查询用户账户余额
				Account findScoreById = am.findScoreById(shareMan.getUserId());
				// 判断用户是否为普通用户
				if (shareMan.getUserType() == 0) {
					// 存入待发现金账户
					this.freezeCashToFormal(1, userId, shareMan.getUserId(), usersUpgrade.getOrderNo(), findScoreById.getFreezeCash(), 1,
							new BigDecimal(configs.getFieldValue()), "被邀请人升级奖励");
					// 修改用户账户待发现金
					this.updateFreezeCash(findScoreById, new BigDecimal(configs.getFieldValue()),isManager,usersUpgrade.getOrderNo());
				} else {
					// 存入正式现金账户
					this.insertLogCash(1, userId, shareMan.getUserId(), usersUpgrade.getOrderNo(), findScoreById.getCash(), "被邀请人升级奖励", 2,
							new BigDecimal(configs.getFieldValue()));
					// 修改用户账户
					this.updateCash(findScoreById, new BigDecimal(configs.getFieldValue()),isManager,usersUpgrade.getOrderNo());
				}
			} else if (usersUpgrade.getPreRole() == 0 && usersUpgrade.getAfterRole() == 2) {
				//查询商城配置中分享人应得现金奖励
				SktSysConfigs configs = sktSysConfigsMapper.selectSysConfigsByFieldCode("commonProfit");
				// 实时查询用户账户余额
				Account findScoreById = am.findScoreById(shareMan.getUserId());
				// 判断用户是否为普通用户
				if (shareMan.getUserType() == 0) {
					// 存入待发现金账户
					this.freezeCashToFormal(1, userId, shareMan.getUserId(), usersUpgrade.getOrderNo(), findScoreById.getFreezeCash(), 1,
							new BigDecimal(configs.getFieldValue()), "被邀请人升级奖励");
					// 修改用户账户待发现金
					this.updateFreezeCash(findScoreById, new BigDecimal(configs.getFieldValue()),isManager,usersUpgrade.getOrderNo());
				} else {
					// 存入正式现金账户
					this.insertLogCash(1, userId, shareMan.getUserId(), usersUpgrade.getOrderNo(), findScoreById.getCash(), "被邀请人升级奖励", 2,
							new BigDecimal(configs.getFieldValue()));
					// 修改用户账户
					this.updateCash(findScoreById, new BigDecimal(configs.getFieldValue()),isManager,usersUpgrade.getOrderNo());
				}
			} else {
				//查询商城配置中分享人应得现金奖励
				SktSysConfigs configs = sktSysConfigsMapper.selectSysConfigsByFieldCode("managerProfit");
				// 实时查询用户账户余额
				Account findScoreById = am.findScoreById(shareMan.getUserId());

				/**
				 *因为这步是从主管升到经理已经给他的上线 发展人数增加过一次，所以这里不做操作应该
				 *先给inviteNum减一，下边会加回来相当于没有操作
				 */
				findScoreById.setInviteNum(findScoreById.getInviteNum()-1);
				// 判断用户是否为普通用户
				if (shareMan.getUserType() == 0) {
					// 存入待发现金账户
					this.freezeCashToFormal(1, userId, shareMan.getUserId(), usersUpgrade.getOrderNo(), findScoreById.getFreezeCash(), 1,
							new BigDecimal(configs.getFieldValue()), "被邀请人升级奖励");
					// 修改用户账户待发现金
					this.updateFreezeCash(findScoreById, new BigDecimal(configs.getFieldValue()),isManager,usersUpgrade.getOrderNo());
				} else {
					// 存入正式现金账户
					this.insertLogCash(1, userId, shareMan.getUserId(), usersUpgrade.getOrderNo(), findScoreById.getCash(), "被邀请人升级奖励", 2,
							new BigDecimal(configs.getFieldValue()));
					// 修改用户账户
					this.updateCash(findScoreById, new BigDecimal(configs.getFieldValue()),isManager,usersUpgrade.getOrderNo());
				}
			}
		}
		/**
		 * 判断用户是否是从普通升主管或是经理
		 */
		//不是主管=》经理
		if (usersUpgrade.getPreRole() != 1){
			//调用方法查看是否有代发奖励，和发展人数(无用)
			//this.selectSpecial(userId,isManager);
		}
		// if (insert == 1 && update == 1) {
		// return "success";
		// }
		//查询用户升级是否当成消费   0:否 1:是
		String isConsume = sktSysConfigsMapper.selectSysConfigsByFieldCode("upgradeProfitFlag").getFieldValue();
		int i = Integer.parseInt(isConsume);
		if(i == 1) {
			//7.买家推荐人消费奖励
			Users userSale = usersMapper.selectById(userId);//获得买家对应的user
			if(userSale.getInviteId()!=0){
				this.saleAward(userSale.getInviteId(), usersUpgrade.getRealMoney().multiply(new BigDecimal(100)),userId,usersUpgrade.getOrderNo());
			}
			//9.特别奖励
			//9.1 消费特别奖

			List<Integer> ids = usersService.getIds(userId);
			if(ids!=null && ids.size()>0){
				SktSysConfigs sysConfig = sktSysConfigsMapper .selectSysConfigsByFieldCode("consumeProfit");
				String fieldValue = sysConfig.getFieldValue();
				BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
				specialAward(ids,percent, usersUpgrade.getRealMoney().multiply(new BigDecimal(100)),1,userSale.getInviteId(),usersUpgrade.getOrderNo());
			}
		}
		return "success";
	}catch (Exception e){
		e.printStackTrace();
		return "error";
	}
	}

	@Transactional
	public Integer updateScoreByUserId(Account account, BigDecimal score) {
		/**
		 * 用户账户表中增加积分
		 */
		// 将用户账户表中积分添加变化金额
		account.setScore(account.getScore().add(score));
		// 将用户获得的积分添加到用户累计获得中去
		account.setTotalScore(account.getTotalScore().add(score));
		// 判断现金是否为空
		// if (cash != null) {
		// // 将用户账户表中积分添加变化金额
		// account.setCash(account.getCash().add(cash));
		// // 将用户获得的积分添加到用户累计获得中去
		// account.setTotalCash(account.getTotalCash().add(cash));
		// }
		// 判断是正常的添加积分，还是待发转入，如果是待发转入，将待发修改成0，不是 待发就改为空
		// if (isFreezeTo) {
		// account.setFreezeScore(new BigDecimal(0));
		// }
		// 判断是否待发转入，如果是待发转入，将待发修改成0，不是待发就改为空
		// if (account.getFreezeCash() != null) {
		// account.setFreezeCash(new BigDecimal(0));
		// }
		// 修改用户账户
		Integer update = am.updateByUserId(account);
		return update;
	}

	// 将待发积分转入正式积分
	@Transactional
	public Integer FreezeToFormal(Integer userId, BigDecimal score, Boolean isManager,String orderNo) {
		LogScore logScore = new LogScore();
		// 支出人为平台设置为0
		logScore.setFromId(userId);
		// 收入人为此用户
		logScore.setUserId(userId);
		// 积分类型为 待发转入正式12    待发中：31转入到正式积分账户
		logScore.setType(12);
		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logScore.setOrderNo(orderNo);
		// 操作前金额要到数据库查询account表中的实时金额，将userId传过去
		Account account = am.findScoreById(userId);
		// 用户操作前金额
		logScore.setPreScore(account.getScore());
		// 流水标志：加积分所以类型为 1   扣除待发积分 -1
		logScore.setScoreType(1);
		// 操作金额
		logScore.setScore(score);
		// 备注
		if (isManager) {
			logScore.setRemark("普通用户升级为经理,划拨特别奖励,积分流水");
			//待发记录生成
			this.insertLogScoreFreeze(userId,31,orderNo,account.getFreezeScore(),"普通用户升级为经理，待发积分转为可用积分",account.getFreezeScore(),-1,userId);
//			this.insertLogScoreFreeze(userId,31,orderNo,account.getFreezeScore(),"普通用户升级为经理，待发积分转为可用积分",account.getFreezeScore(),-1,userId);
//			this.insertLogScoreFreeze(userId,31,orderNo,account.getFreezeScore(),"普通用户升级为经理，待发积分转为可用积分",account.getFreezeScore(),-1,userId);
		} else {
			logScore.setRemark("普通用户升级为主管,划拨特别奖励,积分流水");
			//待发记录生成
			this.insertLogScoreFreeze(userId,31,orderNo,account.getFreezeScore(),"普通用户升级为主管，待发积分转为可用积分",account.getFreezeScore(),-1,userId);
		}
		// 创建时间
		logScore.setCreateTime(new Date());
		// 添加积分记录
		Integer insert = logScoreMapper.insert(logScore);
		// 将待发积分改为零
		account.setFreezeScore(new BigDecimal(0));
		// 将用户账户表中积分添加变化金额
		account.setScore(account.getScore().add(score));
		// 将用户获得的积分添加到用户累计获得中去
		account.setTotalScore(account.getTotalScore().add(score));
		// 修改用户账户
		Integer update = am.updateByUserId2(account);
		return update;
	}

	/**   插入待发积分流水
	 * @param fromId
	 * @param preScore
	 * @param remark
	 * @param score
	 * @param scoreType
	 * @param userId
	 * @return
	 */
	@Override
	@Transactional
	public boolean insertLogScoreFreeze(int fromId, int type,String orderNo,BigDecimal preScore,String remark,BigDecimal score,int scoreType,int userId){
		LogScoreFreeze logScoreFreeze=new LogScoreFreeze();
		logScoreFreeze.setCreateTime(new Date());
		logScoreFreeze.setDataFlag(1);
		logScoreFreeze.setFromId(fromId);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logScoreFreeze.setOrderNo(orderNo);
		logScoreFreeze.setPreScore(preScore);
		logScoreFreeze.setRemark(remark);
		logScoreFreeze.setScore(score);
		logScoreFreeze.setScoreType(scoreType);
		logScoreFreeze.setUserId(userId);
		logScoreFreeze.setType(type);
		Integer flag = logScoreFreezeMapper.insert(logScoreFreeze);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}

	// 将待发现金转入正式
	@Transactional
	public Integer cashFrrezeToFormal(Integer userId, BigDecimal cash, Boolean isManager,String orderNo) {
		// 生成现金流水
		LogCash logCash = new LogCash();
		logCash.setCashType(1);
		logCash.setCreateTime(new Date());
		logCash.setDataFlag(1);
		logCash.setFromId(userId);
		logCash.setUserId(userId);
		// 创建订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate3 = sfDate.format(new Date());
//		String num3 = GetOrderNum.getRandom620(2);
		logCash.setOrderNo(orderNo);
		// 操作前金额要到数据库查询account表中的实时金额，将userId传过去
		Account account = am.findScoreById(userId);
		logCash.setPreCash(account.getCash());
		if (isManager) {
			logCash.setRemark("普通用户升级为经理，待发现金转为可用现金");
		} else {
			logCash.setRemark("普通用户升级为主管，待发现金转为可用现金");
		}
		logCash.setType(4);
		logCash.setCash(account.getFreezeCash());
		logCashMapper.insert(logCash);
		// 将待发积分该为零
		account.setFreezeCash(new BigDecimal(0));
		// 将用户账户表中积分添加变化金额
		account.setCash(account.getCash().add(cash));
		// 将用户获得的积分添加到用户累计获得中去
		account.setTotalCash(account.getTotalCash().add(cash));
		// 修改用户账户
		Integer update = am.updateByUserId3(account);
		return update;
	}

	// 代发现金记录
	@Transactional
	public Integer freezeCashToFormal(Integer type,Integer fromId,Integer
			userId,String orderNo, BigDecimal preCash,
									  Integer cashType, BigDecimal cash, String remark) {
		LogCashFreeze logCashFreeze = new LogCashFreeze();
		logCashFreeze.setType(type);
		logCashFreeze.setFromId(fromId);
		logCashFreeze.setUserId(userId);
		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logCashFreeze.setOrderNo(orderNo);
		// 操作前金额
		logCashFreeze.setPreCash(preCash);
		logCashFreeze.setCashType(cashType);
		logCashFreeze.setCash(cash);
		logCashFreeze.setRemark(remark);
		logCashFreeze.setCreateTime(new Date());
		// 添加待发现金记录
		Integer insert = logCashFreezeMapper.insert(logCashFreeze);
		return insert;
	}

	// 华宝营业额流水表
	@Transactional
	public Integer hbTurnover(Integer type, Integer fromId, Integer userId, String orderNo, Integer kaiyuanType,
							  BigDecimal kaiyuan, String remark) {
		LogKaiyuanTurnover logKaiyuanTurnover = new LogKaiyuanTurnover();
		logKaiyuanTurnover.setType(type);
		logKaiyuanTurnover.setFromId(fromId);
		logKaiyuanTurnover.setUserId(userId);
		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logKaiyuanTurnover.setOrderNo(orderNo);
		// 实时查询用户操作前金额
		AccountShop findKaiyuanTurnover = accountShopMapper.findKaiyuanTurnover(userId);
		// 操作前金额
		logKaiyuanTurnover.setPreKaiyuan(findKaiyuanTurnover.getKaiyuanTurnover());
		// k流水标志
		logKaiyuanTurnover.setKaiyuanType(kaiyuanType);
		logKaiyuanTurnover.setKaiyuan(kaiyuan);
		logKaiyuanTurnover.setRemark(remark);
		logKaiyuanTurnover.setCreateTime(new Date());
		// 添加记录
		Integer insert = logKaiyuanTurnoverMapper.insert(logKaiyuanTurnover);
		// 修改商家账户表
		this.updateKaiyuanByuserId(findKaiyuanTurnover, kaiyuan);
		return insert;
	}

	/**
	 * 修改商家账户表
	 */
	@Transactional
	public Integer updateKaiyuanByuserId(AccountShop findKaiyuanTurnover, BigDecimal kaiyuan) {
		// 添加华宝货款
		findKaiyuanTurnover.setKaiyuanTurnover(findKaiyuanTurnover.getKaiyuanTurnover().add(kaiyuan));
		// 增加累计获得华宝货款
		findKaiyuanTurnover.setTotalKaiyuanTurnover(findKaiyuanTurnover.getTotalKaiyuanTurnover().add(kaiyuan));
		// 将待发华宝货款清零
		findKaiyuanTurnover.setFreezeKaiyuan(new BigDecimal(0));
		Integer update = accountShopMapper.updateKaiyuanByuserId(findKaiyuanTurnover);
		return update;
	}

	/**
	 * 查询前7个工作日申请代理通过
	 * @return
	 */
	@Override
	public List<AgentsApplys> getAgentsApplysSevenAgo(Integer userId){
		Map<String,Object> map=getSevenWorkDay();
		map.put("userId",userId);
		List<AgentsApplys> list = agentsApplysMapper.getAgentsApplysSevenAgo(map);
		return  list;
	}

	//查询前7个工作日
	@Override
	public  Map<String,Object> getSevenWorkDay(){
		Map<String,Object> map=new HashMap<>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		String format = sdf.format(new Date());
		Integer date=Integer.parseInt(format);
		List<SktDate> days = am.getSevenWorkDay(date);
		int endDay=0;
		int startDay=0;
		if(days!=null && days.size()>0){
			endDay=days.get(0).getDate();
			startDay=days.get(days.size()-1).getDate();
		}
		String startDay1=startDay+"";
		String startYaer=startDay1.substring(0,4);
		String startMouth=startDay1.substring(4,6);
		String startDate=startDay1.substring(6,8);
		String newStart=startYaer+"-"+startMouth+"-"+startDate+" "+"00:00:00";
		String endDay1=endDay+"";
		String endYaer=endDay1.substring(0,4);
		String endMouth=endDay1.substring(4,6);
		String endDate=endDay1.substring(6,8);
		String newEnd=endYaer+"-"+endMouth+"-"+endDate+" "+"23:59:59";
		map.put("startDay",newStart);
		map.put("endDay",newEnd);
		return  map;
	}

	/**   插入积分流水
	 * @param fromId
	 * @param preScore
	 * @param remark
	 * @param score
	 * @param scoreType
	 * @param userId
	 * @return
	 */
	@Override
	@Transactional
	public boolean insertLogScore(int fromId,int type, String orderNo,BigDecimal preScore,String remark,BigDecimal score,int scoreType,int userId){
		LogScore logScore=new LogScore();
		logScore.setCreateTime(new Date());
		logScore.setDataFlag(1);
		logScore.setFromId(fromId);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logScore.setOrderNo(orderNo);
		logScore.setPreScore(preScore);
		logScore.setRemark(remark);
		logScore.setScore(score);
		logScore.setScoreType(scoreType);
		logScore.setType(type);
		logScore.setUserId(userId);
		Integer flag = logScoreMapper.insert(logScore);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}
	// 修改用户待发现金
	@Transactional
	public Integer updateFreezeCash(Account account, BigDecimal freezeCash,boolean isMamager,String orderNo) {
		account.setFreezeCash(account.getFreezeCash().add(freezeCash));
		account.setInviteNum(account.getInviteNum() + 1);
		// 修改
		Integer update = am.updateFreezeCash(account);
		//false 说明上线是普通用户要将特别奖励放到待发积分里边
		this.selectSpecial2(account.getUserId(),false,isMamager,orderNo);
		return update;
	}

	/**  现金流水
	 * @param cashType
	 * @param fromId
	 * @param userId
	 * @param firstNum
	 * @param preCash
	 * @param remark
	 * @param type
	 * @param cash
	 * @return
	 */
	@Override
	@Transactional
	public boolean insertLogCash(Integer cashType,Integer fromId,Integer userId ,String orderNo,BigDecimal preCash,String remark,Integer type,BigDecimal cash){
		LogCash logCash=new LogCash();
		logCash.setCashType(cashType);
		logCash.setCreateTime(new Date());
		logCash.setDataFlag(1);
		logCash.setFromId(fromId);
		logCash.setUserId(userId);
		// 创建订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logCash.setOrderNo(orderNo);
		logCash.setPreCash(preCash);
		logCash.setRemark(remark);
		logCash.setType(type);
		logCash.setCash(cash);
		int flag=logCashMapper.insert(logCash);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}

	// 修改用户现金
	@Transactional
	public Integer updateCash(Account account, BigDecimal cash,boolean isManager,String orderNo){
		account.setCash(account.getCash().add(cash));
		account.setTotalCash(account.getTotalCash().add(cash));
		account.setInviteNum(account.getInviteNum() + 1);
		// 修改
		Integer update = am.updateCash(account);
		//true 说明上线不是普通用户要将特别奖励放到正式积分里边
		this.selectSpecial2(account.getUserId(),true,isManager,orderNo);
		return update;
	}

	//下线升级，发放待发特别奖励
	@Transactional
	public Integer selectSpecial2(Integer userId,Boolean b,Boolean isManager,String orderNo){
		//需要取出来的特别积分总金额
		BigDecimal score = new BigDecimal(0);
		//实时查询用户账户
		Account account = am.findScoreById(userId);
		//待发特别奖励操作前金额
		BigDecimal preScore = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour()).add(account.getFive());
		if(account.getInviteNum() > 0 && account.getInviteNum() < 6){
			if(account.getInviteNum() == 1 && account.getOne().compareTo(new BigDecimal(0))==1){
				score = account.getOne();
				account.setOne(new BigDecimal(0));
			}else if(account.getInviteNum() == 2 && account.getTwo().compareTo(new BigDecimal(0))==1){
				score = account.getTwo();
				account.setTwo(new BigDecimal(0));
			}else if(account.getInviteNum() == 3 && account.getThree().compareTo(new BigDecimal(0))==1){
				score = account.getThree();
				account.setThree(new BigDecimal(0));
			}else if(account.getInviteNum() == 4 && account.getFour().compareTo(new BigDecimal(0))==1){
				score = account.getFour();
				account.setFour(new BigDecimal(0));
			}else if(account.getInviteNum() == 5 && account.getFive().compareTo(new BigDecimal(0))==1){
				score = account.getFive();
				account.setFive(new BigDecimal(0));
			}
			if(score.compareTo(new BigDecimal(0))==1){
				//b 为true 说明上线不是普通用户放到正式账户
				if(b){
					if(isManager){
						//生成特别奖励转出记录
						this.insertLogScoreSpecial(31,userId,orderNo,preScore,"普通用户升级为经理，划拨特别奖励,转到正式账号的特别奖励",score,-1,userId);
						//生成积分流水
						this.insertLogScore(userId,15,orderNo,account.getScore(),"普通用户升级为经理,划拨特别奖励,积分流水",score,1,userId);
						//修改用户账户
						account.setScore(account.getScore().add(score));
						account.setTotalScore(account.getTotalScore().add(score));
						Integer update = am.updateScore(account);
						return update;
					}else{
						//生成特别奖励转出记录
						this.insertLogScoreSpecial(31,userId,orderNo,preScore,"普通用户升级为主管，划拨特别奖励,转到正式账号的特别奖励",score,-1,userId);
						//生成积分流水
						this.insertLogScore(userId,15,orderNo,account.getScore(),"普通用户升级为主管,划拨特别奖励,积分流水",score,1,userId);
						//修改用户账户
						account.setScore(account.getScore().add(score));
						account.setTotalScore(account.getTotalScore().add(score));
						Integer update = am.updateScore(account);
						return update;
					}
				}else {
					//上线为普通用户
					if(isManager){
						//生成特别奖励转出记录
						this.insertLogScoreSpecial(31, userId, orderNo, preScore, "普通用户升级为经理，划拨特别奖励,转到待发账号的特别奖励", score, -1, userId);
						//生成待发积分流水
						this.insertLogScoreFreeze(userId, 8, orderNo, account.getFreezeScore(), "普通用户升级为经理,划拨特别奖励,待发积分流水", score, 1, userId);
						//修改用户账户
						account.setFreezeScore(account.getFreezeScore().add(score));
						Integer update = am.updateScore(account);
						return update;
					}else{
						//生成特别奖励转出记录
						this.insertLogScoreSpecial(31, userId, orderNo, preScore, "普通用户升级为主管，划拨特别奖励,转到待发账号的特别奖励", score, -1, userId);
						//生成待发积分流水
						this.insertLogScoreFreeze(userId, 8, orderNo, account.getFreezeScore(), "普通用户升级为主管,划拨特别奖励,待发积分流水", score, 1, userId);
						//修改用户账户
						account.setFreezeScore(account.getFreezeScore().add(score));
						Integer update = am.updateScore(account);
						return update;
					}

				}
			}
		}
		return 0;
	}

	/**   插入特别奖励积分流水
	 * @param fromId
	 * @param preScore
	 * @param remark
	 * @param score
	 * @param scoreType
	 * @param userId
	 * @return
	 */
	@Transactional
	public boolean insertLogScoreSpecial( int type,int fromId, String orderNo,BigDecimal preScore,String remark,BigDecimal score,int scoreType,int userId){
		LogScoreSpecial logScoreSpecial=new LogScoreSpecial();
		logScoreSpecial.setType(type);
		logScoreSpecial.setCreateTime(new Date());
		logScoreSpecial.setDataFlag(1);
		logScoreSpecial.setFromId(fromId);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logScoreSpecial.setOrderNo(orderNo);
		logScoreSpecial.setPreScore(preScore);
		logScoreSpecial.setRemark(remark);
		logScoreSpecial.setScore(score);
		logScoreSpecial.setScoreType(scoreType);
		logScoreSpecial.setUserId(userId);
		Integer flag = logScoreSpecialMapper.insert(logScoreSpecial);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}

//	@Transactional
//	public Integer selectSpecial(Integer userId,Boolean isManager){
//		//需要取出来的代发积分总金额
//		BigDecimal score = new BigDecimal(0);
//		//实时查询用户账户
//		Account account = am.findScoreById(userId);
//		//待发特别奖励操作前金额
//		BigDecimal preScore = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour()).add(account.getFive());
//		if(account.getInviteNum() > 0 && account.getInviteNum() < 6){
//			if(account.getInviteNum() == 1 && account.getOne().compareTo(new BigDecimal(0))==1){
//				score = account.getOne();
//				account.setOne(new BigDecimal(0));
//			}else if(account.getInviteNum() == 2 && account.getTwo().compareTo(new BigDecimal(0))==1){
//				score = account.getOne().add(account.getTwo());
//				account.setOne(new BigDecimal(0));
//				account.setTwo(new BigDecimal(0));
//			}else if(account.getInviteNum() == 3 && account.getThree().compareTo(new BigDecimal(0))==1){
//				score = account.getOne().add(account.getTwo()).add(account.getThree());
//				account.setOne(new BigDecimal(0));
//				account.setTwo(new BigDecimal(0));
//				account.setThree(new BigDecimal(0));
//			}else if(account.getInviteNum() == 4 && account.getFour().compareTo(new BigDecimal(0))==1){
//				score = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour());
//				account.setOne(new BigDecimal(0));
//				account.setTwo(new BigDecimal(0));
//				account.setThree(new BigDecimal(0));
//				account.setFour(new BigDecimal(0));
//			}else if(account.getInviteNum() == 5 && account.getFive().compareTo(new BigDecimal(0))==1){
//				score = account.getOne().add(account.getTwo()).add(account.getThree()).add(account.getFour()).add(account.getFive());
//				account.setOne(new BigDecimal(0));
//				account.setTwo(new BigDecimal(0));
//				account.setThree(new BigDecimal(0));
//				account.setFour(new BigDecimal(0));
//				account.setFive(new BigDecimal(0));
//			}
//			if(score.compareTo(new BigDecimal(0))==1){
//				if(isManager){
//					//生成待发转出记录
//					this.insertLogScoreSpecial(31,userId,"3",preScore,"普通用户升级为经理，划拨特别奖励,转到待发账号的特别奖励",score,-1,userId);
//					//生成积分流水
//					this.insertLogScore(userId,15,"3",account.getScore(),"普通用户升级为经理,划拨特别奖励,积分流水",score,1,userId);
//				}else{
//					//生成待发转出记录
//					this.insertLogScoreSpecial(31,userId,"3",preScore,"普通用户升级为主管，划拨特别奖励,转到待发账号的特别奖励",score,-1,userId);
//					//生成积分流水
//					this.insertLogScore(userId,15,"3",account.getScore(),"普通用户升级为主管,划拨特别奖励,积分流水",score,1,userId);
//				}
//				//修改用户账户
//				account.setScore(account.getScore().add(score));
//				account.setTotalScore(account.getTotalScore().add(score));
//				Integer update = am.updateScore(account);
//				return update;
//			}
//		}
//		return 0;
//	}
	/** 华宝流水
	 * @param fromId
	 * @param kaiyuan
	 * @param kaiyuanType
	 * @param orderNo
	 * @param preKaiyuan
	 * @param remark
	 * @param type
	 * @param userId
	 * @return
	 */
	@Override
	public boolean insertLogKaiyuan(Integer fromId,BigDecimal kaiyuan,Integer kaiyuanType,String orderNo,BigDecimal preKaiyuan,String remark,Integer type,Integer userId){
		LogKaiyuan logKaiyuan=new LogKaiyuan();
		logKaiyuan.setCreateTime(new Date());
		logKaiyuan.setFromId(fromId);
		logKaiyuan.setKaiyuan(kaiyuan);
		logKaiyuan.setKaiyuanType(kaiyuanType);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logKaiyuan.setOrderNo(orderNo);
		logKaiyuan.setPreKaiyuan(preKaiyuan);
		logKaiyuan.setRemark(remark);
		logKaiyuan.setType(type);
		logKaiyuan.setUserId(userId);
		int flag=logKaiyuanMapper.insert(logKaiyuan);//华宝消费记录
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}

	//商家华宝货款记录
	@Override
	public Integer insertLogKaiYuanTurnover(Integer type,Integer fromId,Integer userId,String orderNo,BigDecimal preKaiyuan,Integer kaiyuanType,BigDecimal kaiyuan,String remark){
		LogKaiyuanTurnover logKaiyuanTurnover = new LogKaiyuanTurnover();
		logKaiyuanTurnover.setType(type);
		logKaiyuanTurnover.setFromId(fromId);
		logKaiyuanTurnover.setUserId(userId);
		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logKaiyuanTurnover.setOrderNo(orderNo);
		logKaiyuanTurnover.setPreKaiyuan(preKaiyuan);
		logKaiyuanTurnover.setKaiyuanType(kaiyuanType);
		logKaiyuanTurnover.setKaiyuan(kaiyuan);
		logKaiyuanTurnover.setRemark(remark);
		logKaiyuanTurnover.setCreateTime(new Date());
		Integer insert = logKaiyuanTurnoverMapper.insert(logKaiyuanTurnover);
		return insert;
	}

	/**
	 * 确认代理申请
	 * @param shaId 股东申请表id
	 * @param staffId  操作员id
	 * @return
	 */
	@Transactional
	public String doUpAgent(Integer shaId,Integer staffId) {
		try{
			AgentsApplys agentsApplys = agentsApplysMapper.selectById(shaId);
			int userId = agentsApplys.getUserId();
			SktAgentsStockholder sktAgentsStockholder = agentsStockholderMapper.selectByUserId(userId);
			if(sktAgentsStockholder!=null){
				return "该用户已经是股东";
			}

			int agentId = agentsApplys.getAgentId();
			int type = agentsApplys.getType();
			SktAgentsAccount agentsAccount =
					agentsAccountMapper.findAgentAccountById(agentId);
			Account account = am.selectAccountByuserId(userId);
			BigDecimal money = agentsApplys.getMoney();
			if (type != 6 && type != 7) {
				SktAgentsStockholder agentsStockholder = new
						SktAgentsStockholder();
				agentsStockholder.setAgentId(agentId);
				agentsStockholder.setType(type);
				Integer countStcokManger =
						agentsStockholderMapper.selectCountStcokManger(agentsStockholder);
				if (type == 1 && countStcokManger == 1) {
					return "董事长职位已满";
				} else if (type == 2 && countStcokManger == 1) {
					return "总裁职位已满";
				} else if (type == 3 && countStcokManger == 1) {
					return "行政职位已满";
				} else if (type == 4 && countStcokManger == 1) {
					return "财务职位已满";
				} else if (type == 5 && countStcokManger == 3) {
					return "部门经理职位已满";
				}
				//修改申请表
				agentsApplys.setBatFlag(1);
				Date batTime = agentsApplys.getBatTime();
				Calendar c = Calendar.getInstance();
				c.setTime(batTime);//设置日历时间
				c.add(Calendar.MONTH, 3);//在日历的月份上增加3个月
				agentsApplys.setTestTime(c.getTime());
				//	agentsApplys.setBatTime(c.getTime());
				agentsApplysMapper.updateById(agentsApplys);
//				insertLogScoreFreeze(0, 2, agentsApplys.getOrderNo(), account.getFreezeScore(), "升级代理", money.multiply(new BigDecimal("100")), 1, userId);
//				account.setFreezeScore(account.getFreezeScore().add(money.multiply(new BigDecimal("100"))));
//				am.updateById(account);

			}
			SktAgents agents = agentsMapper.selectById(agentId);
			SktAgentsStockholder agentsStockholder = new
					SktAgentsStockholder();
			agentsStockholder.setAgentId(agentId);
			agentsStockholder.setType(type);
			if (type == 7) {
				if( agents.getLPsurplusStockNum() ==0){
					return "普通股东已满";
				}
				//修改申请表
				agentsApplys.setTwoCheckTime(new Date());
				agentsApplys.setStatus(3);
				agentsApplys.setTwoCheckStaffId(staffId);
				agentsApplysMapper.updateById(agentsApplys);
			}
			Users users = usersMapper.selectById(userId);
			users.setIsAgent(type);
			usersMapper.updateById(users);//修改用户代理状态
			Integer countIsStore = usersMapper.selectCountIsStore
					(userId);
			//生成代理公司股东表
			agentsStockholder.setCreateTime(new Date());
			agentsStockholder.setStockNum(agentsApplys.getStockNum());
			agentsStockholder.setStoreNum(countIsStore);
			agentsStockholder.setUserId(userId);
			agentsStockholderMapper.insert(agentsStockholder);
			//修改代理公司表
			agents.setStockNum(agents.getStockNum() + 1);
			agents.setStoreNum(agents.getStoreNum() + countIsStore);
			if(type==7){
				agents.setLPsurplusStockNum(agents.getLPsurplusStockNum() -
						agentsApplys.getStockNum());
			}else if(type==5){
				agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-2);
			}else if(type==4){
				agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-3);
			}else if(type==3){
				agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-3);
			}else if(type==2){
				agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-4);
			}else if(type==1){
				agents.setGPsurplusStockNum(agents.getGPsurplusStockNum()-5);
			}
			agentsMapper.updateById(agents);
			//修改代理公司账户表
			if (agentsAccount.getRunFlag() == 1) {//代理公司账号是否开启
				//代理公司积分流水表
				insertScoreAgent(1, agentId, agentsApplys.getOrderNo(),
						agentsAccount.getScore(), 1, money.multiply(new BigDecimal("100")), "股东申请通过，代理公司获得");
				agentsAccount.setScore(agentsAccount.getScore
						().add(money.multiply(new BigDecimal("100"))));
				agentsAccount.setTotalScore
						(agentsAccount.getTotalScore().add(money.multiply(new BigDecimal("100"))));
			} else {
				//代理公司待发流水表
				insertLogScoreFreeze(0, 2, agentsApplys.getOrderNo(),
						agentsAccount.getFreezeScore(), "升级代理", money.multiply(new BigDecimal("100")), 1,
						agentId);
				agentsAccount.setFreezeScore
						(agentsAccount.getFreezeScore().add(money.multiply(new BigDecimal("100"))));
			}
			agentsAccountMapper.updateById(agentsAccount);
			//给自己发积分
			BigDecimal score = money.multiply(new BigDecimal("100"));

//				int countNotHolder =
//						agentsStockholderMapper.selectCountNotHolder(agentId);

//				if (countNotHolder <= 3) {
//					score = money.multiply(new BigDecimal("200"));
//				} else {
//					score = money.multiply(new BigDecimal("100"));
//				}

			//给自己添加   的积分流水
			this.insertLogScore(0, 9, agentsApplys.getOrderNo(), account.getScore(), "升级代理公司股东，赠送积分到积分账户", score, 1, userId);
			account.setScore(account.getScore().add(score));
			account.setTotalScore(account.getTotalScore().add(score));
			am.updateById(account);

			//给上线发积分（经理或者代理）
			int inviteId = users.getInviteId();
			if (inviteId != 0) {
				Users inviteUsers = usersMapper.selectById
						(inviteId);
				if (inviteUsers.getUserType() == 2 &&
						inviteUsers.getIsAgent() != 0) {
					Account accountInvite =
							am.selectAccountByuserId(inviteId);
					BigDecimal doubelScore = money.multiply(new
							BigDecimal("200"));
					this.insertLogScore(userId, 10, agentsApplys.getOrderNo(),
							accountInvite.getScore(), "下线升级代理奖励", doubelScore, 1, inviteId);
					accountInvite.setScore
							(accountInvite.getScore().add(doubelScore));
					accountInvite.setTotalScore
							(accountInvite.getTotalScore().add(doubelScore));
					am.updateById(accountInvite);
				}
			}
			//如果是主管申请代理判断下线7个工作日内是否有代理申请通过
			if (users.getUserType() == 1) {
				List<AgentsApplys> list = getAgentsApplysSevenAgo
						(userId);
				if (list != null && list.size() > 0) {
					BigDecimal sumScore = BigDecimal.ZERO;
					BigDecimal sumScoreFreeze =
							BigDecimal.ZERO;
					for (AgentsApplys AgentsApply : list) {
						if (AgentsApply.getType() == 7) {
							sumScore = sumScore.add
									(AgentsApply.getMoney().multiply(new BigDecimal("200")));
						} else if (AgentsApply.getType() !=
								7 && AgentsApply.getType() != 6) {
							sumScoreFreeze =
									sumScoreFreeze.add(AgentsApply.getMoney().multiply(new BigDecimal("200")));
						}
					}
					if(sumScoreFreeze.compareTo(BigDecimal.ZERO)==1){
						this.insertLogScoreFreeze(userId, 10, agentsApplys.getOrderNo(),
								account.getFreezeScore(), "下线升级代理奖励", sumScoreFreeze, 1, userId);
						account.setFreezeScore
								(account.getFreezeScore().add(sumScoreFreeze));
					}
					if(sumScore.compareTo(BigDecimal.ZERO)==1){
						this.insertLogScore(userId, 10, agentsApplys.getOrderNo(),
								account.getScore(), "下线升级代理奖励", sumScore, 1, userId);
						account.setScore(account.getScore().add
								(sumScore));
						account.setTotalScore
								(account.getTotalScore().add(sumScore));
					}
					am.updateById(account);
				}
			}
				this.fenRun(agentId,shaId);

			return "操作成功";
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "操作失败";
		}

	}
	/**
	 * 代理申请成功分润
	 * @param agentId 代理id
	 * @param shaId  股东申请id
	 */
	@Override
	public void fenRun(Integer agentId,Integer shaId){

		SktAgentsAccount agentsAccount=agentsAccountMapper.findAgentAccountById(agentId);
		AgentsApplys agentsApplys = agentsApplysMapper.selectById(shaId);
		BigDecimal money=agentsApplys.getMoney();
		SktAgents agents = agentsMapper.selectById(agentId);
		BigDecimal a=new BigDecimal(agents.getStockNum());
		BigDecimal b=new BigDecimal(agents.getTotalStockNum());
		Double f=a.divide(b, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
		SktSysConfigs sysConfig = sktSysConfigsMapper.selectSysConfigsByFieldCode("holderDividendNum");
		String fieldValue = sysConfig.getFieldValue();
		Integer holderDividendNum=Integer.parseInt(fieldValue);
		if(agentsAccount.getRunFlag()==0){
			if(f>=0.5){
				this.insertScoreAgent(32,agentId,agentsApplys.getOrderNo(),agentsAccount.getScore(),1,agentsAccount.getFreezeScore(),"待发积分转正式积分");
				insertLogScoreFreeze(0,2,agentsApplys.getOrderNo(),agentsAccount.getFreezeScore(),"待发积分转正式积分",money.multiply(new BigDecimal("100")),-1,agentId);
				agentsAccount.setRunFlag(1);
				agentsAccount.setScore(agentsAccount.getScore().add(agentsAccount.getFreezeScore()));
				agentsAccount.setTotalScore(agentsAccount.getTotalScore().add(agentsAccount.getFreezeScore()));
				agentsAccount.setFreezeScore(BigDecimal.ZERO);
				agentsAccountMapper.updateById(agentsAccount);

			}
		}
		BigDecimal c=new BigDecimal(agents.getStoreNum());
		BigDecimal d=new BigDecimal(agents.getTotalStoreNum());
		double perStore= c.divide(d,2, BigDecimal.ROUND_HALF_UP).doubleValue();
		if(f>=0.7 && perStore>=0.7){
			List<SktAgentsStockholder> list = agentsStockholderMapper.selectByAgentId(agentId);
			if(list!=null && list.size()>0){
				BigDecimal twoFreezeDividend=list.get(0).getTwoFreezeDividend();
				if(twoFreezeDividend.compareTo(BigDecimal.ZERO)==1){
					for (SktAgentsStockholder agentsStockholder:list){
						Integer userId=agentsStockholder.getUserId();
						int totalStockNum=agents.getTotalStockNum();
						BigDecimal twoRatio=agents.getTwoRatio();
						int stockNum=agentsStockholder.getStockNum();
						Account account = am.selectAccountByuserId(userId);
						Integer countIsStore = usersMapper.selectCountIsStore(userId);
						if(countIsStore>=holderDividendNum){
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTwoFreezeDividend(),"70%(落地)之前冻结分红转出",agentsStockholder.getTwoFreezeDividend(),-1,userId);
							this.insertLogScore(userId,11,agentsApplys.getOrderNo(),agentsStockholder.getTwoFreezeDividend(),"70%(落地)之前冻结分红转入",agentsStockholder.getTwoFreezeDividend(),1,userId);

							account.setScore(account.getScore().add(agentsStockholder.getTwoFreezeDividend()));
							account.setTotalScore(account.getTotalScore().add(agentsStockholder.getTwoFreezeDividend()));
							agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
							am.updateById(account);
							agentsStockholderMapper.updateById(agentsStockholder);
						}else{
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTotalDividend(),"70%(落地)之前冻结分红转出",agentsStockholder.getTotalDividend(),1,userId);
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTotalDividend(),"70%(落地)之前冻结分红转入",agentsStockholder.getTotalDividend(),-1,userId);
							agentsStockholder.setStoreFreezeDividend(agentsStockholder.getStoreFreezeDividend().add(agentsStockholder.getTwoFreezeDividend()));
							agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
							agentsStockholderMapper.updateById(agentsStockholder);
						}


					}

				}
			}
		}
		if(f>=1.0 && perStore>=1.0){
			List<SktAgentsStockholder> list = agentsStockholderMapper.selectByAgentId(agentId);
			if(list!=null && list.size()>0){
				BigDecimal threeFreezeDividend=list.get(0).getThreeFreezeDividend();
				if(threeFreezeDividend.compareTo(BigDecimal.ZERO)>=0){
					for (SktAgentsStockholder agentsStockholder:list){
						Integer userId=agentsStockholder.getUserId();
						int totalStockNum=agents.getTotalStockNum();
						BigDecimal twoRatio=agents.getTwoRatio();
						int stockNum=agentsStockholder.getStockNum();
						Account account = am.selectAccountByuserId(userId);
						Integer countIsStore = usersMapper.selectCountIsStore(userId);
						if(countIsStore>=holderDividendNum){
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getThreeFreezeDividend(),"70%(落地)之前冻结分红转出",agentsStockholder.getThreeFreezeDividend(),-1,userId);
							this.insertLogScore(userId,11,agentsApplys.getOrderNo(),agentsStockholder.getThreeFreezeDividend(),"70%(落地)之前冻结分红转入",agentsStockholder.getThreeFreezeDividend(),1,userId);

							account.setScore(account.getScore().add(agentsStockholder.getThreeFreezeDividend()));
							account.setTotalScore(account.getTotalScore().add(agentsStockholder.getThreeFreezeDividend()));
							agentsStockholder.setTwoFreezeDividend(BigDecimal.ZERO);
							am.updateById(account);
							agentsStockholderMapper.updateById(agentsStockholder);
						}else{
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTotalDividend(),"70%(落地)之前冻结分红转出",agentsStockholder.getTotalDividend(),1,userId);
							this.insertLogScoreFreeze(userId,33,agentsApplys.getOrderNo(),agentsStockholder.getTotalDividend(),"70%(落地)之前冻结分红转入",agentsStockholder.getTotalDividend(),-1,userId);
							agentsStockholder.setStoreFreezeDividend(agentsStockholder.getStoreFreezeDividend().add(agentsStockholder.getThreeFreezeDividend()));
							agentsStockholder.setThreeFreezeDividend(BigDecimal.ZERO);
							agentsStockholderMapper.updateById(agentsStockholder);
						}

					}
				}
			}
		}
	}
	//代理公司积分记录
	public Integer insertScoreAgent(Integer type,Integer agentId,String orderNo,BigDecimal preScore,Integer scoreType,BigDecimal score,String remark){
		LogScoreAgent logScoreAgent = new LogScoreAgent();
		logScoreAgent.setType(type);
		logScoreAgent.setAgentId(agentId);
		// 生成订单号
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logScoreAgent.setOrderNo(orderNo);
		logScoreAgent.setPreScore(preScore);
		logScoreAgent.setScoreType(scoreType);
		logScoreAgent.setScore(score);
		logScoreAgent.setRemark(remark);
		logScoreAgent.setCreateTime(new Date());
		logScoreAgent.setDataFlag(1);
		Integer insert = logScoreAgentMapper.insert(logScoreAgent);
		return insert;
	}

	/**
	 * 购买牌匾审核通过
	 * @param orderId
	 * @return
	 */
	@Override
	public boolean applysBuyplaqueTrue(Integer orderId){
		try{
			SktBuyplaque sktBuyplaque = sktBuyplaqueMapper.selectById(orderId);
			BigDecimal sumScore=sktBuyplaque.getTotalMoney().multiply(new BigDecimal(100));
			Integer userId = sktBuyplaque.getUserId();
			Account account = am.selectAccountByuserId(userId);
			//1.买家积分流水
			this.insertLogScore(0,16,sktBuyplaque.getOrderNo(), account.getScore(), "购买牌匾奖励", sumScore, 1, userId);
			//2.买家账户表修改
			account.setOnlineExpenditure(account.getOnlineExpenditure().add(sktBuyplaque.getTotalMoney()));
			account.setScore(account.getScore().add(sumScore));
			account.setTotalScore(account.getTotalScore().add(sumScore));
			am.updateById(account);
			//7.买家推荐人消费奖励
			Users userSale = usersMapper.selectById(userId);//获得买家对应的user
			if(userSale.getInviteId()!=0){
				this.saleAward(userSale.getInviteId(), sumScore,userId,sktBuyplaque.getOrderNo());
			}
			//9.特别奖励
			//9.1 消费特别奖

			List<Integer> ids = usersService.getIds(userId);
			if(ids!=null && ids.size()>0){
				SktSysConfigs sysConfig = sktSysConfigsMapper .selectSysConfigsByFieldCode("consumeProfit");
				String fieldValue = sysConfig.getFieldValue();
				BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
				specialAward(ids,percent, sumScore,1,userSale.getInviteId(),sktBuyplaque.getOrderNo());
			}
			return true;
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}
	}

	/**
	 * 后台审核购买牌匾取消
	 * @param orderId
	 * @return
	 */
	@Override
	public  boolean applysBuyplaqueFalse(Integer orderId){
		try{
			SktBuyplaque sktBuyplaque = sktBuyplaqueMapper.selectById(orderId);
			Integer payType = sktBuyplaque.getPayType();
			BigDecimal sumScore=sktBuyplaque.getTotalMoney().multiply(new BigDecimal(100));
			Integer userId = sktBuyplaque.getUserId();
			Account account = am.selectAccountByuserId(userId);
			if (payType==1||payType==2||payType==4){ //现金账户
				this.insertLogCash(1,0,userId,sktBuyplaque.getOrderNo(),account.getCash(),"购买牌匾",38,sktBuyplaque.getCash());
				account.setCash(account.getCash().add(sktBuyplaque.getTotalMoney()));
				account.setTotalCash(account.getTotalCash().add(sktBuyplaque.getTotalMoney()));
				am.updateById(account);
			}else if (payType==3){ //华宝支付
				this.insertLogKaiyuan(0,sktBuyplaque.getKaiyuan(),38,sktBuyplaque.getOrderNo(),account.getKaiyuan(),"购买牌匾",1,userId);
				this.insertLogKaiyuan(0,sktBuyplaque.getKaiyuanFee(),39,sktBuyplaque.getOrderNo(),account.getKaiyuan(),"购买牌匾的手续费和税率",1,userId);
				account.setKaiyuan(account.getKaiyuan().add(sktBuyplaque.getKaiyuan()).add(sktBuyplaque.getKaiyuanFee()));
				am.updateById(account);
			}else if (payType==6){//华宝货款
				AccountShop accountShop=new AccountShop();
				accountShop.setUserId(userId);
				EntityWrapper<AccountShop> ew=new EntityWrapper<AccountShop>(accountShop);
				AccountShop accountShop1 = accountShopService.selectOne(ew);
				this.insertLogKaiYuanTurnover(1,0,userId,sktBuyplaque.getOrderNo(),accountShop1.getKaiyuanTurnover(),38,sktBuyplaque.getKaiyuan(),"购买牌匾");
				this.insertLogKaiYuanTurnover(1,0,userId,sktBuyplaque.getOrderNo(),accountShop1.getKaiyuanTurnover(),39,sktBuyplaque.getKaiyuanFee(),"购买牌匾的手续费和税率");
				accountShop1.setKaiyuanTurnover(accountShop1.getKaiyuanTurnover().add(sktBuyplaque.getKaiyuan()).add(sktBuyplaque.getKaiyuanFee()));
				accountShopService.updateById(accountShop1);
			}
			return  true;
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}

	}
	/**
	 * 销售奖励
	 * @param inviteId
	 * @param score
	 * @param userId
	 * @return
	 */
	public Integer marketAward(int inviteId,BigDecimal score, int userId){
		Account account=am.selectAccountByuserId(inviteId);//推荐人账户
		Users user = usersMapper.selectById(inviteId);//推荐人
		int userType =user.getUserType();
		SktSysConfigs sysConfig = sktSysConfigsMapper.selectSysConfigsByFieldCode("turnoverProfit");
		String fieldValue = sysConfig.getFieldValue();
		BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
		BigDecimal getScore=score.multiply(percent);

		if(userType==0){
			//代发积分流水
			this.insertLogScoreFreeze(userId,5,"1",account.getFreezeScore(),"线下商家消费获得",getScore,2,inviteId);
			account.setFreezeScore(account.getFreezeScore().add(getScore));
		}else{
			//积分流水
			this.insertLogScore(userId, 5,"1", account.getScore(), "下线营业额获得", getScore, 2, inviteId);
			account.setTotalScore(account.getTotalScore().add(getScore));
			account.setScore(account.getScore().add(getScore));
		}
		return	am.updateById(account);
	}

	/** 消费奖励
	 * @param inviteId 推荐人id
	 *   @param  score   积分
	 * @return
	 */
	public Integer saleAward(int inviteId,BigDecimal score,int usetId ,String orderNo){
		Account account=am.selectAccountByuserId(inviteId);//推荐人账户
		Users user = usersMapper.selectById(inviteId);//推荐人
		int userType =user.getUserType();
		SktSysConfigs sysConfig = sktSysConfigsMapper.selectSysConfigsByFieldCode("consumeProfit");
		String fieldValue = sysConfig.getFieldValue();
		BigDecimal percent=new BigDecimal(fieldValue).divide(new BigDecimal(100));
		BigDecimal getScore=score.multiply(percent);

		if(userType==0){
			//代发积分流水
			this.insertLogScoreFreeze(usetId,4,orderNo,account.getFreezeScore(),"下线消费获得",getScore,4,inviteId);
			account.setFreezeScore(account.getFreezeScore().add(getScore));
		}else{
			//积分流水
			this.insertLogScore(usetId, 4,orderNo, account.getScore(), "下线消费获得", getScore, 1, inviteId);
			account.setScore(account.getScore().add(getScore));
			account.setTotalScore(account.getTotalScore().add(getScore));
		}
		return	am.updateById(account);
	}
	/**   特别奖励
	 * @param list
	 * @param specialPer
	 * @param score
	 * @param specialType

	 * @return
	 */
	public void specialAward(List<Integer> list,BigDecimal specialPer,BigDecimal score,Integer specialType,int inviteId,String orderNo){
		BigDecimal score1=score.multiply(specialPer);
		SktSysConfigs sysConfig = sktSysConfigsMapper.selectSysConfigsByFieldCode("specialProfit");
		BigDecimal specialProfit=new BigDecimal(sysConfig.getFieldValue()).divide(new BigDecimal(100));;
		//特别奖励
		String specialFirstNum="";
		String specialRemark="";
		int specialScoreType=0;
		//待发积分
		String ScoreFreezefirstNum="";
		int  ScoreFreezeType=0;
		String ScoreFreezeRemark="";
		int   ScoreFreezeScoreType=0;
		//积分流水
		String  scoreFirstNum="";
		String   scoreRemark="";
		int  scoreType=0;
		int  scoreScoreType=0;

		if (specialType==1){//1消费获得的待发特别奖励
			specialFirstNum="1";
			specialRemark="消费获得的待发特别奖励";
			specialScoreType=1;
			ScoreFreezefirstNum="1";
			ScoreFreezeType=6;
			ScoreFreezeRemark="特别奖励";
			ScoreFreezeScoreType=1;
			scoreType=6;
			scoreFirstNum="3";
			scoreRemark="特别奖励";
			scoreScoreType=1;
		}
		if (specialType==2){//消售获得的待发特别奖励
			specialFirstNum="1";
			specialRemark="消售获得的待发特别奖励";
			specialScoreType=1;
			ScoreFreezefirstNum="6";
			ScoreFreezeType=6;
			ScoreFreezeRemark="特别奖励";
			ScoreFreezeScoreType=1;
			scoreType=6;
			scoreFirstNum="3";
			scoreRemark="特别奖励";
			scoreScoreType=1;
		}
		if (specialType==31){//31转到正式账号的特别奖励
			specialFirstNum="3";
			specialRemark="转到正式账号的特别奖励";
			specialScoreType=-1;

			ScoreFreezefirstNum="3";
			ScoreFreezeType=31;
			ScoreFreezeRemark="转入到正式积分账户";
			ScoreFreezeScoreType=-1;

			scoreType=15;
			scoreFirstNum="3";
			scoreRemark="待发特别奖励转入";
			scoreScoreType=1;
		}
		if(list.size()>0){
			int i=-1;
			for(Integer id:list){
				if( i!=-1){
					inviteId=list.get(i);
				}
				i++;
				score1=score1.multiply(specialProfit);
				if(score1.compareTo(new BigDecimal("1"))==-1){
					break;
				}
				Users user = usersMapper.selectById(id);//推荐人
				Account account = am.selectAccountByuserId(id);//推荐人账户
				BigDecimal preFreezeScore=new BigDecimal("0.0000");
				if(account.getFreezeScore()!=null){
					preFreezeScore=account.getFreezeScore();
				}
				BigDecimal preScore=new BigDecimal("0.0000");
				if(account.getScore()!=null){
					preScore=account.getScore();
				}
				BigDecimal preScoreSpecial=new BigDecimal("0.00");

				if(account.getOne()!=null){
					preScoreSpecial= preScoreSpecial.add(account.getOne());
				}
				if(account.getTwo()!=null){
					preScoreSpecial= preScoreSpecial.add(account.getTwo());
				}
				if(account.getThree()!=null){
					preScoreSpecial=  preScoreSpecial.add(account.getThree());
				}
				if(account.getFour()!=null){
					preScoreSpecial=preScoreSpecial.add(account.getFour());
				}
				if(account.getFive()!=null){
					preScoreSpecial= preScoreSpecial.add(account.getFive());
				}
				int inviteNum=account.getInviteNum();

				if (user.getUserType()==0){ //普通用户
					if (inviteNum>=5){ //推荐主管或者经理人数大于等于5
						//待发积分流水------
						insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score1,ScoreFreezeScoreType, id);
						account.setFreezeScore(account.getFreezeScore().add(score1));
						account.setTotalScore(account.getTotalScore().add(score1));
						am.updateById(account);
					}else {
						BigDecimal score2=score1.divide(new BigDecimal(5));
						if(inviteNum==0){
							account.setOne(account.getOne().add(score2));
							account.setTwo(account.getTwo().add(score2));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}else if(inviteNum==1){
							insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score2,ScoreFreezeScoreType, id);

							account.setFreezeScore(account.getFreezeScore().add(score2));

							account.setTwo(account.getTwo().add(score2));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}else if(inviteNum==2){
							insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score2.multiply(new BigDecimal(2)),ScoreFreezeScoreType, id);

							account.setFreezeScore(account.getFreezeScore().add(score2.multiply(new BigDecimal(2))));

							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}else if(inviteNum==3){
							insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score2.multiply(new BigDecimal(3)),ScoreFreezeScoreType, id);
							account.setFreezeScore(account.getFreezeScore().add(score2.multiply(new BigDecimal(3))));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}else if(inviteNum==4){
							insertLogScoreFreeze(inviteId,ScoreFreezeType, orderNo,preFreezeScore,ScoreFreezeRemark,score2.multiply(new BigDecimal(4)),ScoreFreezeScoreType, id);
							account.setFreezeScore(account.getFreezeScore().add(score2.multiply(new BigDecimal(4))));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}
						//待发特别奖励积分流水---------------------
						insertLogScoreSpecial(specialType,inviteId, orderNo,preScoreSpecial,specialRemark,score1, specialScoreType,id);
					}
				}else{
					if (inviteNum>=5){ //推荐主管或者经理人数大于等于5
						//积分流水------
						insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score1,scoreScoreType,id);
						account.setScore(account.getScore().add(score1));
						account.setTotalScore(account.getTotalScore().add(score1));
						am.updateById(account);
					}else {
						BigDecimal score2=score1.divide(new BigDecimal(5));
						if(inviteNum==0){
							account.setOne(account.getOne().add(score2));
							account.setTwo(account.getTwo().add(score2));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}else if(inviteNum==1){
							insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score2,scoreScoreType,id);
							account.setScore(account.getScore().add(score2));
							account.setTotalScore(account.getTotalScore().add(score2));
							account.setTwo(account.getTwo().add(score2));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}else if(inviteNum==2){
							insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score2.multiply(new BigDecimal(2)),scoreScoreType,id);
							account.setScore(account.getScore().add(score2.multiply(new BigDecimal(2))));
							account.setTotalScore(account.getTotalScore().add(score2.multiply(new BigDecimal(2))));
							account.setThree(account.getThree().add(score2));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}else if(inviteNum==3){
							insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score2.multiply(new BigDecimal(3)),scoreScoreType,id);
							account.setScore(account.getScore().add(score2.multiply(new BigDecimal(3))));
							account.setTotalScore(account.getTotalScore().add(score2.multiply(new BigDecimal(3))));
							account.setFour(account.getFour().add(score2));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}else if(inviteNum==4){
							insertLogScore(inviteId,scoreType, orderNo,preScore,scoreRemark,score2.multiply(new BigDecimal(4)),scoreScoreType,id);
							account.setScore(account.getScore().add(score2.multiply(new BigDecimal(4))));
							account.setTotalScore(account.getTotalScore().add(score2.multiply(new BigDecimal(4))));
							account.setFive(account.getFive().add(score2));
							am.updateById(account);
						}
						//待发特别奖励积分流水---------------------
						insertLogScoreSpecial(specialType,inviteId, orderNo,preScoreSpecial,specialRemark,score1, specialScoreType,id);
					}
				}
				//
			}
		}

	}
	/*
	 * 取消代理升级
	 *
	 */
	@Transactional
	@Override
	public boolean resetAgentUPGrade(AgentsApplys agentsApplys){
		try {
			Account account = am.selectAccountBuyuserId(agentsApplys.getUserId());
				this.insertLogCash(1, 0, agentsApplys.getUserId(), agentsApplys.getOrderNo(), account.getCash(), "订单"+agentsApplys.getOrderNo()  +"退款", 35, agentsApplys.getMoney());
				BigDecimal cash2 = account.getCash().add( agentsApplys.getMoney());
				account.setCash(cash2);
				am.updateById(account);
			return true;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return false;
		}
	}

	/**
	 * 提现拒绝
	 * @param usersDraws
	 * @return
	 */
	@Override
	public  boolean applyRedeemFalse(UsersDraws usersDraws){
		try{
				int userId=	usersDraws.getUserId();
				Account account=new Account();
				account.setUserId(userId);
				EntityWrapper<Account> ew =new EntityWrapper<Account>(account);
				Account account1 = this.selectOne(ew);
				BigDecimal totalMoney=usersDraws.getMoney().add(usersDraws.getFee());
				if (usersDraws.getType()==1){  //华宝赎回
					//华宝流水（33赎回支出 34赎回的手续费和税率）
					this.insertLogKaiyuan(0,account1.getKaiyuan(),1,usersDraws.getDrawNo(),usersDraws.getMoney(),"提现拒绝退还 ",2,userId);
					this.insertLogKaiyuan(0,account1.getKaiyuan(),1,usersDraws.getDrawNo(),usersDraws.getFee(),"提现拒绝手续费退还 ",3,userId);
					account1.setKaiyuan(account1.getKaiyuan().add(totalMoney));
					this.updateById(account1);
				}else if (usersDraws.getType()==2){ //现金赎回
					//31提现支出 36提现手续费
					this.insertLogCash(1,0,userId,usersDraws.getDrawNo(),account1.getCash(),"提现拒绝退还",5,usersDraws.getMoney());
					this.insertLogCash(1,0,userId,usersDraws.getDrawNo(),account1.getCash(),"提现拒绝手续费退还 ",8,usersDraws.getFee());
					account1.setCash(account1.getCash().add(totalMoney));
					this.updateById(account1);
				}else if (usersDraws.getType()==3){
					AccountShop accountShop=new AccountShop();
					accountShop.setUserId(userId);
					EntityWrapper<AccountShop> ewp =new EntityWrapper<AccountShop>(accountShop);
					AccountShop accountShop1 = accountShopService.selectOne(ewp);
					//33赎回支出 34赎回的手续费和税率
					this.insertLogKaiYuanTurnover(2,0,userId,usersDraws.getDrawNo(),accountShop1.getKaiyuanTurnover(),-1,usersDraws.getMoney(),"营业额赎回退还");
					this.insertLogKaiYuanTurnover(3,0,userId,usersDraws.getDrawNo(),accountShop1.getKaiyuanTurnover(),-1, usersDraws.getFee(),"营业额赎回手续费和税率退还");
					accountShop1.setKaiyuanTurnover(accountShop1.getKaiyuanTurnover().add(totalMoney));
					accountShopService.updateById(accountShop1);
				}
			return  true;
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return  false;
		}
	}

	/**
	 * 用户申请退货平台同意后返还到积分账户
	 * @param sktOrderRefunds
	 * @return
	 */
	@Override
	public  boolean enterOrderRefunds(SktOrderRefunds sktOrderRefunds){
		try{
			SktOrders sktOrders = som.selectById(sktOrderRefunds.getOrderId());
			Integer userId = sktOrderRefunds.getRefundTo();
			Account account=new Account();
			account.setUserId(userId);
			EntityWrapper<Account> entityWrapper=new EntityWrapper<Account>(account);
			Account account1 = this.selectOne(entityWrapper);
			this.insertLogCash(1, 0,userId, sktOrders.getOrderNo(), account1.getCash(), "订单"+sktOrders.getOrderNo()  +"退款", 5, sktOrderRefunds.getBackMoney());
			BigDecimal cash2 = account1.getCash().add(sktOrderRefunds.getBackMoney());
			account1.setCash(cash2);
			am.updateById(account1);
			return  true;
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return  false;
		}
	}
	/** 待发华宝营业额流水
	 * @param fromId
	 * @param kaiyuan
	 * @param kaiyuanType
	 * @param orderNo
	 * @param preKaiyuan
	 * @param remark
	 * @param type
	 * @param userId
	 * @return
	 */
	public boolean insertLogKaiyuanFreeze(Integer fromId,BigDecimal kaiyuan,Integer kaiyuanType,String orderNo,BigDecimal preKaiyuan,String remark,Integer type,Integer userId){
		LogKaiyuanFreeze logKaiyuanFreeze=new LogKaiyuanFreeze();
		logKaiyuanFreeze.setCreateTime(new Date());
		logKaiyuanFreeze.setFromId(fromId);
		logKaiyuanFreeze.setKaiyuan(kaiyuan);
		logKaiyuanFreeze.setKaiyuanType(kaiyuanType);
//		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String strDate = sfDate.format(new Date());
//		String num = GetOrderNum.getRandom620(2);
		logKaiyuanFreeze.setOrderNo(orderNo);
		logKaiyuanFreeze.setPreKaiyuan(preKaiyuan);
		logKaiyuanFreeze.setRemark(remark);
		logKaiyuanFreeze.setType(type);
		logKaiyuanFreeze.setUserId(userId);
		int flag=logKaiyuanFreezeMapper.insert(logKaiyuanFreeze);//代发华宝消费记录
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}
}
